<?php
/**
 * @author fld 2021-06-16
 * @desc 登陆日志业务类
 */
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;
use App\Service\Admin\AdminService;

class AdminLoginlogService
{
    /**
     * @author fld 2021-06-16
     * @desc 添加登录日志信息
     * @param $data
     * @return int
     */
    public function addAdminLoginLog($data){
        $insert_data = [];
        $insert_data['admin_name'] = !empty($data['username']) ? $data['username'] : '';
        $insert_data['status'] = $data['status'];
        if($data['status'] == 1){
            $insert_data['true_name'] = !empty($data['true_name']) ? $data['true_name'] : '';
            $insert_data['remark'] = '登录成功';
        }else{
            $adminService = new AdminService();
            $admin_info = $adminService->getAdminByCondition(['admin_name'=>$data['username']]);
            if(empty($admin_info)){
                $insert_data['true_name'] = '';
            }else{
                $insert_data['true_name'] = $admin_info['true_name'];
            }
            $insert_data['remark'] = $data['remark'];
        }
        $insert_data['action_time'] = time();
        $insert_data['action_ip'] = $data['login_ip'];
        $id = DB::table('admin_loginlog')->insertGetId($insert_data);
        return $id;
    }

    /**
     * @author fld 2021-06-18
     * @desc 登录日志分页列表
     * @return array
     */
    public function getLogListByPage(){
        $params = request()->all();
        $condition = $this->getSearchCondition();
        $list = DB::table('admin_loginlog')->where($condition)->orderBy('id','desc')->paginate(10);
        $pager = $list->links();
        return ['list' => $list, 'pager' => $pager, 'params'=>$params];
    }

    /**
     * @author fld 2021-06-17
     * @desc 查询条件
     * @return array
     */
    public function getSearchCondition(){
        $condition = [];
        $params = request()->all();
        if(!empty($params['name'])){
            $condition[] = ['admin_name','like','%'.$params['name'].'%'];
        }
        if(!empty($params['true_name'])){
            $condition[] = ['true_name','like','%'.$params['true_name'].'%'];
        }
        if(isset($params['status']) && strlen($params['status']) > 0){
            $condition[] = ['status','=', $params['status']];
        }
        if(!empty($params['begin_time'])){
            $condition[] = ['action_time','>=', strtotime($params['begin_time'])];
        }
        if(!empty($params['end_time'])){
            $condition[] = ['action_time','<=', strtotime($params['end_time'])];
        }
        return $condition;
    }
}